<template>
  <div class="case">
    <el-button type="primary" @click="openDialog()">新增楼盘</el-button>

    <el-table border :data="tableData" v-loading="loading" style="width: 100%">
      <el-table-column prop="id" label="序号" width="180"></el-table-column>
      <el-table-column
        prop="title"
        label="楼盘标题"
        width="180"
      ></el-table-column>
      <el-table-column prop="content" label="楼盘图片">
        <!-- 使用 v-slot 替代 slot-scope -->
        <template #default="scope">
          <div class="news-images">
            <img
              v-if="getFirstImage(scope.row.content)"
              :src="getFirstImage(scope.row.content)"
              alt
              style="
                width: 100%;
                height: auto;
                max-height: 100px;
                object-fit: cover;
              "
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="content" label="楼盘内容">
        <template #default="scope">
          <div v-if="stripImages(scope.row.content).length > 100">
            <div
              v-html="stripImages(scope.row.content).slice(0, 100) + '...'"
            ></div>
          </div>
          <div v-else v-html="stripImages(scope.row.content)"></div>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
            type="primary"
            @click="handleEdit(scope.$index, scope.row)"
          >
            <!-- 使用 ElIcon 组件包裹图标 -->
            <el-icon>
              <Edit />
            </el-icon>
          </el-button>
          <el-button
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
          >
            <el-icon>
              <Delete />
            </el-icon>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 使用 v-model 替代 :visible.sync -->
    <el-dialog title="楼盘编辑" v-model="dialogFormVisible">
      <el-form :model="formData">
        <el-form-item label="楼盘标题" :label-width="formLabelWidth">
          <el-input v-model="formData.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="楼盘内容" :label-width="formLabelWidth">
          <el-upload
            ref="hiddenUpload"
            class="hidden-upload"
            name="image"
            :action="uploadImg"
            :headers="headers"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
          ></el-upload>
          <QuillEditorComponent
            ref="quillEditorRef"
            :content="formData.content"
            :uploadImg="uploadImg"
            :headers="headers"
            :imgServer="imgServer"
          />
        </el-form-item>
      </el-form>
      <!-- 使用 v-slot 定义底部插槽 -->
      <template #footer>
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleCreateOrModify()"
          >确 定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { Edit, Delete } from "@element-plus/icons-vue";
import QuillEditorComponent from "../../components/QuillEditorComponent.vue";

export default {
  components: {
    Edit,
    Delete,
    QuillEditorComponent,
  },
  data() {
    return {
      loading: true,
      dialogFormVisible: false,
      formLabelWidth: "120px",
      tableData: [],
      formData: {
        id: 0,
        img: "",
        title: "",
        content: "",
        del: "",
        createTime: new Date(),
      },
      options: {},
      headers: {},
    };
  },
  mounted() {
    let token = "Browser " + sessionStorage.getItem("token");
    this.options = {
      headers: {
        Authorization: token,
      },
    };
    this.headers = {
      Authorization: token,
    };
    this.loadData();
  },
  methods: {
    handleSuccess(response) {
      this.formData.img = response.files[0];
    },
    async loadData() {
      this.loading = true;
      try {
        const response = await this.$http.get("case/all", this.options);
        this.tableData = response.data;
      } catch (e) {
        this.$message.error("网络或程序异常！" + e);
      } finally {
        this.loading = false;
      }
    },
    openDialog() {
      if (this.formData.content !== "") {
        this.$refs.quillEditorRef.clearEditorContent();
      }
      this.formData = {
        id: 0,
        img: "",
        title: "",
        content: "",
        del: "",
        createTime: new Date(),
      };
      this.dialogFormVisible = true;
    },
    handleCreateOrModify() {
      if (!this.formData.id) {
        this.loading = true;
        this.$http
          .post("case/create", this.formData, this.options)
          .then((response) => {
            this.loading = false;
            this.$message.success("创建成功！");
            this.dialogFormVisible = false;
            this.loadData();
          })
          .catch((e) => {
            this.$message.error("网络或程序异常！" + e);
          });
      } else {
        this.loading = true;
        this.$http
          .put("case/update", this.formData, this.options)
          .then((response) => {
            this.loading = false;
            this.$message.success("修改成功！");
            this.dialogFormVisible = false;
            this.loadData();
          })
          .catch((e) => {
            this.$message.error("网络或程序异常！" + e);
          });
      }
    },
    handleEdit(index, row) {
      this.formData = { ...row };
      this.dialogFormVisible = true;
    },
    handleDelete(index, row) {
      this.$messageBox
        .confirm("此操作将永久删除此条数据, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(() => {
          this.loading = true;
          this.$http
            .delete(`case/delete/${row.id}`, this.options)
            .then((response) => {
              this.loading = false;
              this.$message.success("删除成功！");
              this.loadData();
            })
            .catch((e) => {
              this.$message.error("网络或程序异常！" + e);
            });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    dateFormat(row) {
      let t = new Date(row.createTime);
      return t.getFullYear() + "-" + (t.getMonth() + 1) + "-" + t.getDate();
    },
    stripImages(html) {
      return html.replace(/<img[^>]*>/g, "");
    },
    getFirstImage(html) {
      const imgRegex = /<img[^>]+src="([^">]+)"/;
      const match = html.match(imgRegex);
      return match ? match[1] : "";
    },
    handleUploadSuccess(response) {
      const imgUrl = this.imgServer + response.files[0];
      const quill = this.$refs.quillEditorRef.quill;
      const range = quill.getSelection();
      if (range) {
        quill.insertEmbed(range.index, "image", imgUrl);
        quill.setSelection(range.index + 1);
      }
    },
  },
};
</script>

<style scoped>
.el-table {
  margin-top: 20px;
}
.avatar {
  width: 300px;
}
</style>
